import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface UserInfo {
  id: string
  name: string
  email: string
  avatar?: string
  role: string
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const isDark = ref(false)
  const sidebarCollapsed = ref(false)
  const userInfo = ref<UserInfo>({
    id: '1',
    name: '管理员',
    email: 'admin@test.com',
    role: 'admin'
  })

  // 计算属性
  const theme = computed(() => isDark.value ? 'dark' : 'light')

  // 动作
  const toggleTheme = () => {
    isDark.value = !isDark.value
    updateTheme()
  }

  const setTheme = (theme: 'light' | 'dark') => {
    isDark.value = theme === 'dark'
    updateTheme()
  }

  const updateTheme = () => {
    const html = document.documentElement
    if (isDark.value) {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }
    localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
  }

  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme')
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    
    if (savedTheme) {
      isDark.value = savedTheme === 'dark'
    } else {
      isDark.value = prefersDark
    }
    
    updateTheme()
  }

  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
  }

  const setUserInfo = (info: Partial<UserInfo>) => {
    userInfo.value = { ...userInfo.value, ...info }
  }

  return {
    // 状态
    isDark,
    sidebarCollapsed,
    userInfo,
    
    // 计算属性
    theme,
    
    // 动作
    toggleTheme,
    setTheme,
    initTheme,
    toggleSidebar,
    setSidebarCollapsed,
    setUserInfo
  }
})

